package com.qf.controller;

import com.qf.utils.Result;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @ClassName UserController
 * @Author xiao宋
 * @Date 21:49  2022/10/10
 * @Version 1.0
 * @Description TODO
 */
@RestController
public class UserController {

    @RequestMapping("/add")
    @RequiresRoles(value = "管理员")
    public void add(){
        System.out.println("add");
    }
    @RequestMapping("/up")
    @RequiresRoles(value = "开发工程师")
    public void up(){
        System.out.println("add");
    }

    @RequestMapping("/dologin")
    public Result login(String username, String password) {

        try {
            Subject subject = SecurityUtils.getSubject();

            Md5Hash hash = new Md5Hash(password, username, 1024);
            UsernamePasswordToken token = new UsernamePasswordToken(username, hash.toString());
            subject.login(token);
        } catch (
                UnknownAccountException e) {
            e.printStackTrace();
            return Result.error("未找到");
        } catch (
                LockedAccountException e) {
            e.printStackTrace();
            return Result.error("用户已失效");
        } catch (
                CredentialsException e) {
            e.printStackTrace();
            return Result.error("密码错误");
        } catch (RuntimeException e) {
            e.printStackTrace();
            return Result.error("用户名不能为空");
        }

        return Result.ok("登录成功");
    }
}
